<?php

class Controller
{
	public $Controller;
	public $Method;
	
	public $Uses = array();	
	public $Stylesheets = array();
	public $Javascripts = array();
	
	private $Json = array();
	
	public $Auth;
	
	public function __construct($Controller, $Method)
	{
		$this->Controller = strtolower($Controller);
		$this->Method = strtolower($Method);
		
		if (is_array($this->Uses) && count($this->Uses) >= 1)
		{
			foreach ($this->Uses as $Key => $Model)
			{
				$File = 'application/models/' . strtolower($Model) . '.php';
				
				if (!file_exists($File))
				{
					die('Model file ' . $File . ' not found.');
				}
				
				require($File);
			}
		}
		
		$this->Auth = new Auth;
	}
	
	public function Initialize()
	{
		return;
	}
	
	public function Permission($Permission)
	{
		return Roles::Check($Permission, $this->Auth->GetRole());
	}
	
	public function AddCssFile($Stylesheet)
	{
		$this->Stylesheets[] = $Stylesheet;
	}
	
	public function AddJsFile($Javascript)
	{
		$this->Javascripts[] = $Javascript;
	}
	
	public function SetJson($Key, $Value)
	{
		$this->Json[$Key] = $Value;
	}
	
	public function Render()
	{
		if (is_array($this->Json) && count($this->Json) >= 1)
		{
			exit(json_encode($this->Json));
		}
		else
		{		
			$View = 'application/views/' . $this->Controller . '/' . $this->Method . '.tpl';
			$Layout = 'application/views/layout.tpl';
			
			if (!file_exists($View))
			{
				die('View file ' . $View . ' not found.');
			}
			
			ob_start();
			require($View);
			$this->Body = ob_get_contents() . "\n";
			ob_end_clean();
			
			require($Layout);
		}
	}
}